Django documentation

2. Adding __repr__() to models

Although it's not a strict requirement, each model should have a __repr__() method to return a "human-readable" representation of the object. Do this not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin.

Model source code

from django.core import meta

class Article(meta.Model):
    headline = meta.CharField(maxlength=100)
    pub_date = meta.DateTimeField()

    def __repr__(self):
        return self.headline

API reference

Article objects have the following methods:

  • delete()
  • get_next_by_pub_date()
  • get_previous_by_pub_date()
  • save()

Sample API usage

This sample code assumes the above model has been saved in a file examplemodel.py.

>>> from django.models.examplemodel import articles

# Create an Article.
>>> from datetime import datetime
>>> a = articles.Article(headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
>>> a.save()

>>> repr(a)
'Area man programs in Python'

>>> a
Area man programs in Python

Comments

Post a comment

Note: Please only use the comments for questions/critcisms/suggestions on the docs; if you experience errors please file a ticket, ask in the IRC channel, or post to the django-users list. Comments will be periodically reviewed, integrated into the documentation proper, and removed.

Your name:

Comment: